package com.lanou3g.code0515.util;

/**
 * Created by dllo on 18/5/15.
 */

import com.lanou3g.code0515.study.TestUUID;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 封装ServletUpLoad
 */
public class SmartUpload {
    private HttpServlet servlet;
    private ServletFileUpload sfu;//用于上传
    private File uploadDir;
    //用来存储普通表单数据
    private HashMap<String, String> parameters;
    //用来存储上传的文件名 和 文件
    private HashMap<String, File> files;

    public SmartUpload(HttpServlet httpServlet) {
        this.servlet = httpServlet;
        //初始化上传文件夹
        initDir();
        sfu = new ServletFileUpload();
        sfu.setFileItemFactory(new DiskFileItemFactory());

        parameters = new HashMap<>();
        files =new HashMap<>();
    }

    private void initDir() {
        String uploadPath = servlet.getServletContext().getRealPath("") + File.separator + "upload";
        uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            //创建文件夹
            uploadDir.mkdirs();
        }
    }


    public void parse(HttpServletRequest request) {
        try {
            List<FileItem> fileItems = sfu.parseRequest(request);

            if (fileItems!=null){
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()){
                        //表单数据
                        String key =fileItem.getFieldName();
                        String value = fileItem.getString("utf-8");
                        parameters.put(key,value);
                    }else {
                        //不是表单数据
                        String fileName = fileItem.getName();
                        //引包引的事apache下的
                        //别导错了
                        if (StringUtils.isEmpty(fileName)) {
                            continue;
                        }

                        String realName = TestUUID.handleFileName(fileName);
                        File file =new File(uploadDir,realName);
                        fileItem.write(file);
                        //数据放到files中
                        files.put(fileName,file);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
/***提供 访问的方法****/
public String getParameter(String key) {
    return  parameters.get(key);
}
public Map<String,String>getParameterMap(){
    return parameters;
}
public  Map<String,File>getUploadedFiles(){
    return  files;
}
}
